package info.batcloud.fanli.core.service.impl;

import info.batcloud.fanli.core.entity.UserLog;
import info.batcloud.fanli.core.repository.UserLogRepository;
import info.batcloud.fanli.core.service.UserLogService;
import org.springframework.stereotype.Service;

import javax.inject.Inject;
import java.util.Date;

@Service
public class UserLogServiceImpl implements UserLogService {

    @Inject
    private UserLogRepository userLogRepository;

    @Override
    /**
     * 记录登录日志，这里最好使用消息队列进行处理 TODO 进行消息队列处理登录日志
     * */
    public LogResult log(LogParam param) {
        UserLog lastLog = userLogRepository.findTop1ByUserIdAndType(param.getUserId(), param.getType());
        UserLog log = new UserLog();
        if (lastLog == null) {
            log.setTotalTimes(1);
        } else {
            log.setTotalTimes(lastLog.getTotalTimes() + 1);
        }
        log.setIp(param.getIp());
        log.setUserId(param.getUserId());
        log.setCreateTime(new Date());
        log.setType(param.getType());
        userLogRepository.save(log);

        LogResult result = new LogResult();
        result.setLastLogTime(log.getCreateTime());
        result.setTotalTimes(log.getTotalTimes());
        return result;
    }
}
